"""
应用配置管理
"""

from pydantic_settings import BaseSettings
from typing import List, Optional
import os
from pathlib import Path


class Settings(BaseSettings):
    """应用设置"""
    
    # 基础配置
    PROJECT_NAME: str = "Offline Language Player"
    PROJECT_DESCRIPTION: str = "离线语言播放系统 - 用于有声读物阅读和视频配音的API服务"
    VERSION: str = "1.0.0"
    API_V1_STR: str = "/api/v1"
    
    # 服务器配置
    HOST: str = "0.0.0.0"
    PORT: int = 8000
    DEBUG: bool = False
    
    # 数据库配置
    DATABASE_URL: str = "sqlite+aiosqlite:///./data/app.db"
    DATABASE_ECHO: bool = False
    
    # Redis配置
    REDIS_URL: str = "redis://localhost:6379/0"
    REDIS_PASSWORD: Optional[str] = None
    REDIS_DB: int = 0
    
    # 安全配置
    SECRET_KEY: str = "your-secret-key-change-in-production"
    ALGORITHM: str = "HS256"
    ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    
    # CORS配置
    BACKEND_CORS_ORIGINS: List[str] = [
        "http://localhost:3000",
        "http://localhost:8080",
        "http://127.0.0.1:3000",
        "http://127.0.0.1:8080"
    ]
    ALLOWED_HOSTS: List[str] = ["*"]
    
    # TTS配置
    DEFAULT_TTS_ENGINE: str = "pyttsx3"
    DEFAULT_VOICE_RATE: int = 200
    DEFAULT_VOICE_VOLUME: float = 0.9
    AUDIO_CACHE_DIR: str = "./data/cache/audio"
    AUDIO_FORMAT: str = "wav"
    AUDIO_SAMPLE_RATE: int = 22050
    
    # 视频处理配置
    VIDEO_CACHE_DIR: str = "./data/cache/video"
    MAX_VIDEO_SIZE: str = "500MB"
    SUPPORTED_VIDEO_FORMATS: List[str] = ["mp4", "avi", "mov", "wmv"]
    
    # 文件上传配置
    MAX_UPLOAD_SIZE: str = "100MB"
    UPLOAD_DIR: str = "./data/uploads"
    ALLOWED_EXTENSIONS: List[str] = ["txt", "pdf", "epub", "mp3", "wav", "mp4", "avi"]
    
    # 日志配置
    LOG_LEVEL: str = "INFO"
    LOG_FILE: str = "./data/logs/app.log"
    LOG_ROTATION: str = "daily"
    LOG_RETENTION: int = 30
    
    # 监控配置
    ENABLE_METRICS: bool = True
    METRICS_PORT: int = 9090
    SENTRY_DSN: Optional[str] = None
    
    # 任务队列配置
    CELERY_BROKER_URL: str = "redis://localhost:6379/1"
    CELERY_RESULT_BACKEND: str = "redis://localhost:6379/2"
    CELERY_TASK_SERIALIZER: str = "json"
    CELERY_RESULT_SERIALIZER: str = "json"
    
    # WebSocket配置
    WEBSOCKET_HEARTBEAT_INTERVAL: int = 30
    WEBSOCKET_MAX_CONNECTIONS: int = 1000
    
    class Config:
        env_file = ".env"
        env_file_encoding = "utf-8"
        case_sensitive = True
        
        @classmethod
        def parse_env_var(cls, field_name: str, raw_val: str) -> any:
            """解析环境变量"""
            if field_name == "BACKEND_CORS_ORIGINS":
                # 解析CORS origins列表
                return [x.strip() for x in raw_val.split(",")]
            elif field_name == "ALLOWED_HOSTS":
                # 解析允许的主机列表
                if raw_val == "*":
                    return ["*"]
                return [x.strip() for x in raw_val.split(",")]
            elif field_name == "ALLOWED_EXTENSIONS":
                # 解析允许的文件扩展名
                return [x.strip() for x in raw_val.split(",")]
            elif field_name == "SUPPORTED_VIDEO_FORMATS":
                # 解析支持的视频格式
                return [x.strip() for x in raw_val.split(",")]
            else:
                return raw_val
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._ensure_directories()
    
    def _ensure_directories(self):
        """确保必要的目录存在"""
        directories = [
            self.AUDIO_CACHE_DIR,
            self.VIDEO_CACHE_DIR,
            self.UPLOAD_DIR,
            os.path.dirname(self.LOG_FILE)
        ]
        
        for directory in directories:
            Path(directory).mkdir(parents=True, exist_ok=True)
    
    @property
    def is_development(self) -> bool:
        """是否为开发环境"""
        return self.DEBUG
    
    @property
    def is_production(self) -> bool:
        """是否为生产环境"""
        return not self.DEBUG
    
    def get_cors_origins(self) -> List[str]:
        """获取CORS origins"""
        if self.is_development:
            return ["*"]
        return self.BACKEND_CORS_ORIGINS
    
    def get_database_url(self) -> str:
        """获取数据库URL"""
        return self.DATABASE_URL
    
    def get_redis_url(self) -> str:
        """获取Redis URL"""
        return self.REDIS_URL


# 创建全局设置实例
settings = Settings()


def get_settings() -> Settings:
    """获取设置实例"""
    return settings
